package com.order.manager.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class JwtUtil {

    //常量
    public static final long EXPIRE = 1000 * 60 * 60 * 24 * 7; //token过期时间7天
    public static final String APP_SECRET = "zxy#@zT^utyyxuoyz;x..yzxdsfdyzdxtvzxy>>zxtzx**y%%z@@xy**"; //秘钥

    /**
     * 获取token
     */
    public String getToken(String uuid) {
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("username", uuid)//设置token主体部分 ，存储用户信息
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
    }

    /**
     * username是user的uuid的别名，是用户唯一标识
     * @param request
     * @return
     */
    public String getJwtUsername(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");//从请求头中获取token
        if (jwtToken != null && !jwtToken.isEmpty() && checkToken(jwtToken)) {
            try {//token可用
                Claims claims = getTokenBody(jwtToken);
                return (String) claims.get("username");
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        } else {
            log.warn("username get fails");
            return null;
        }
        return null;
    }

        public String getJwtUsernameByJwt(String  token) {
        if (token != null && !token.isEmpty() && checkToken(token)) {
            try {//token可用
                Claims claims = getTokenBody(token);
                return (String) claims.get("username");
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        } else {
            log.warn("username get fails");
            return null;
        }
        return null;
    }




    /**
     * 验证token字符串是否是有效的  包括验证是否过期
     * @param jwtToken
     * @return
     */
    public boolean checkToken(String jwtToken) {
        if (jwtToken == null || jwtToken.isEmpty()) {
            log.error("Jwt is empty");
            return false;
        }
        try {
            Jws<Claims> claims = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
            Claims body = claims.getBody();
            if (body.getExpiration().after(new Date(System.currentTimeMillis()))) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    public Claims getTokenBody(String jwtToken) {
        if (jwtToken == null || jwtToken.isEmpty()) {
            log.error("Jwt is empty");
            return null;
        }
        try {
            return Jwts.parser().setSigningKey(APP_SECRET).
                    parseClaimsJws(jwtToken).getBody();
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }
}